package com.moli.iov.admin.service.impl;

import com.moli.iov.admin.component.CacheManger;
import com.moli.iov.admin.model.vo.req.UserVo;
import com.moli.iov.admin.service.IAuthenticationFacadeService;
import com.moli.iov.admin.service.ILoginLogFacadeService;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.sys.model.dto.req.AuthenticationDto;
import com.moli.iov.sys.model.dto.res.LoginDto;
import com.moli.iov.sys.model.po.Permission;
import com.moli.iov.sys.remote.IAuthenticationRemoteService;
import com.moli.iov.util.CommonUtils;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 身份认证
 * </p>
 *
 * @author zql
 * @since 2019/9/26 12:40
 */
@Slf4j
@Service
public class AuthenticationFacadeServiceImpl implements IAuthenticationFacadeService {

  @Reference(group = "${service.group}", check = false)
  private IAuthenticationRemoteService authenticationRemoteService;

  @Autowired
  private CacheManger cacheManger;

  @Autowired
  private ILoginLogFacadeService loginLogFacadeService;

  /**
   * 登陆
   * @param request
   * @param userVo
   * @return
   */
  @Override
  public RestResponse login(HttpServletRequest request, UserVo userVo) {
    LoginDto loginDto = null;
    RestResponse<LoginDto> restResponse = RestResponse.success();
    try {
      AuthenticationDto authenticationDto = new AuthenticationDto();
      CommonUtils.copyProperties(userVo, authenticationDto);

      restResponse = authenticationRemoteService.login(authenticationDto);
      if(!restResponse.flag){
        return restResponse;
      }

      loginDto = restResponse.getData();

      cacheManger.setLoginCache(loginDto);

      loginDto.setApiPermissions(null);

      restResponse.setData(loginDto);
    }catch(Exception e){
      log.error("登陆 ", e);
      restResponse = RestResponse.failure("登录失败");
    }

    loginLogFacadeService.save(userVo, loginDto, restResponse.flag, request);
    return restResponse;
  }

  /**
   * 鉴权
   * @param request
   * @param account
   * @return
   */
  @Override
  public boolean auth(HttpServletRequest request, String account) {
    try {

      Map<String, Permission> permissions = cacheManger.getPermission(account);

      Permission permission = permissions.get(request.getRequestURI());
      if(permission == null || permission.getPermissionId() == null){
        return false;
      }
      return true;
    }catch (BusinessException e){
      log.info("鉴权 {}", e.getMessage());
      return false;
    }catch (Exception e){
      log.error("鉴权 异常", e);
      throw new BusinessException("无此权限");
    }
  }

  /**
   * 登出
   * @param token
   */
  @Override
  public void logout(String token) {
    cacheManger.setLogoutToken(token);
  }
}
